<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG MVP Service - Demo</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
        }
        
        h1 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        
        .section {
            margin-bottom: 40px;
        }
        
        .section h2 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.5em;
        }
        
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            background: #e9ecef;
            border-color: #764ba2;
        }
        
        .upload-area.dragover {
            background: #e7f3ff;
            border-color: #667eea;
        }
        
        input[type="file"] {
            display: none;
        }
        
        .btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        
        .btn:hover {
            background: #764ba2;
        }
        
        .btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .query-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .query-input {
            flex: 1;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
        }
        
        .query-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .file-controls {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .file-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        .file-table th,
        .file-table td {
            border: 1px solid #e9ecef;
            padding: 10px;
            text-align: left;
        }

        .file-table th {
            background: #f8f9fa;
        }

        .file-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .btn.secondary {
            background: #6c757d;
        }

        .btn.danger {
            background: #dc3545;
        }

        .btn.secondary:hover {
            background: #5a6268;
        }

        .btn.danger:hover {
            background: #b52a37;
        }

        .result {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        
        .result h3 {
            color: #333;
            margin-bottom: 15px;
        }
        
        .answer {
            background: white;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            line-height: 1.6;
        }
        
        .evidence-item {
            background: white;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 10px;
            border-left: 3px solid #764ba2;
        }
        
        .evidence-meta {
            font-size: 0.9em;
            color: #666;
            margin-top: 10px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #667eea;
        }
        
        .status {
            padding: 10px;
            border-radius: 6px;
            margin-bottom: 20px;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 RAG MVP Service</h1>
        <p class="subtitle">Upload documents and ask questions</p>
        
        <div class="section">
            <h2>📄 Upload Document</h2>
            <div class="upload-area" id="uploadArea">
                <p>Click to select or drag and drop a file (.txt, .md, .pdf)</p>
                <input type="file" id="fileInput" accept=".txt,.md,.pdf">
            </div>
            <div id="uploadStatus"></div>
        </div>
        
        <div class="section">
            <h2>❓ Ask a Question</h2>
            <div class="query-form">
                <input 
                    type="text" 
                    id="questionInput" 
                    class="query-input" 
                    placeholder="Enter your question here..."
                >
                <button class="btn" id="queryBtn" onclick="query()">Query</button>
            </div>
            <div id="queryResult"></div>
        </div>

        <div class="section">
            <h2>📚 Document Management</h2>
            <div class="file-controls">
                <button class="btn secondary" onclick="fetchFiles()">Refresh List</button>
            </div>
            <div id="fileListStatus"></div>
            <div id="fileList"></div>
        </div>
    </div>
    
    <script>
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const uploadStatus = document.getElementById('uploadStatus');
        const questionInput = document.getElementById('questionInput');
        const queryBtn = document.getElementById('queryBtn');
        const queryResult = document.getElementById('queryResult');
        const fileListContainer = document.getElementById('fileList');
        const fileListStatus = document.getElementById('fileListStatus');
        
        // File upload handling
        uploadArea.addEventListener('click', () => fileInput.click());
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                uploadFile();
            }
        });
        
        fileInput.addEventListener('change', uploadFile);
        
        async function uploadFile() {
            const file = fileInput.files[0];
            if (!file) return;
            
            const formData = new FormData();
            formData.append('file', file);
            
            uploadStatus.innerHTML = '<div class="loading">Uploading...</div>';
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    uploadStatus.innerHTML = `
                        <div class="status success">
                            ✅ Upload successful! File ID: ${data.file_id}, Chunks: ${data.chunks}
                        </div>
                    `;
                } else {
                    const errorDetail = data.detail || data.message || 'Upload failed';
                    uploadStatus.innerHTML = `
                        <div class="status error">
                            ❌ Error: ${errorDetail}
                            ${errorDetail.includes('404') || errorDetail.includes('page not found') ? 
                                '<br><small>💡 Tip: DeepSeek may not support embeddings API. Try using OpenAI for embeddings or check your API configuration.</small>' : ''}
                        </div>
                    `;
                }
            } catch (error) {
                uploadStatus.innerHTML = `
                    <div class="status error">
                        ❌ Error: ${error.message}
                    </div>
                `;
            }
        }
        
        questionInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                query();
            }
        });
        
        async function query() {
            const question = questionInput.value.trim();
            if (!question) {
                alert('Please enter a question');
                return;
            }
            
            queryBtn.disabled = true;
            queryResult.innerHTML = '<div class="loading">Searching...</div>';
            
            try {
                const response = await fetch('/query', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        question: question,
                        top_k: 4
                    })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    let html = '<div class="result">';
                    html += `<h3>Answer</h3>`;
                    html += `<div class="answer">${data.answer || 'No answer generated'}</div>`;
                    
                    if (data.evidence && data.evidence.length > 0) {
                        html += `<h3>Evidence (${data.evidence.length} chunks)</h3>`;
                        data.evidence.forEach((item, idx) => {
                            html += `
                                <div class="evidence-item">
                                    <strong>Chunk ${idx + 1}</strong>
                                    <p>${item.chunk || ''}</p>
                                    <div class="evidence-meta">
                                        Distance: ${item.distance !== null ? item.distance.toFixed(4) : 'N/A'} | 
                                        File: ${item.meta?.filename || 'Unknown'}
                                    </div>
                                </div>
                            `;
                        });
                    }
                    html += '</div>';
                    queryResult.innerHTML = html;
                } else {
                    queryResult.innerHTML = `
                        <div class="status error">
                            ❌ Error: ${data.detail || 'Query failed'}
                        </div>
                    `;
                }
            } catch (error) {
                queryResult.innerHTML = `
                    <div class="status error">
                        ❌ Error: ${error.message}
                    </div>
                `;
            } finally {
                queryBtn.disabled = false;
            }
        }

        async function fetchFiles() {
            fileListStatus.innerHTML = '<div class="loading">Loading files...</div>';
            fileListContainer.innerHTML = '';
            try {
                const response = await fetch('/files');
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.detail || 'Failed to fetch files');
                }
                renderFileList(data.files || []);
                fileListStatus.innerHTML = `<div class="status success">Loaded ${data.total || 0} file(s)</div>`;
            } catch (error) {
                fileListStatus.innerHTML = `
                    <div class="status error">
                        ❌ Error: ${error.message}
                    </div>
                `;
            }
        }

        function renderFileList(files) {
            if (!files.length) {
                fileListContainer.innerHTML = '<p>No files uploaded yet.</p>';
                return;
            }

            let html = `
                <table class="file-table">
                    <thead>
                        <tr>
                            <th>File ID</th>
                            <th>Filename</th>
                            <th>Chunks</th>
                            <th>Uploaded</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            files.forEach(file => {
                const inputId = `updateFile-${file.file_id}`;
                html += `
                    <tr>
                        <td style="word-break: break-all">${file.file_id}</td>
                        <td>${file.filename}</td>
                        <td>${file.chunk_count}</td>
                        <td>${file.upload_time || '-'}</td>
                        <td>
                            <div class="file-actions">
                                <button class="btn secondary" onclick="document.getElementById('${inputId}').click()">Update</button>
                                <button class="btn danger" onclick="deleteFile('${file.file_id}')">Delete</button>
                                <input type="file" id="${inputId}" style="display:none" accept=".txt,.md,.pdf"
                                    onchange="handleUpdateFile(event, '${file.file_id}')">
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table>';
            fileListContainer.innerHTML = html;
        }

        async function deleteFile(fileId) {
            if (!confirm('Delete this file? This action cannot be undone.')) return;

            fileListStatus.innerHTML = '<div class="loading">Deleting...</div>';
            try {
                const response = await fetch(`/files/${fileId}`, { method: 'DELETE' });
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.detail || 'Failed to delete file');
                }
                fileListStatus.innerHTML = `
                    <div class="status success">
                        ✅ ${data.message || 'File deleted'}
                    </div>
                `;
                fetchFiles();
            } catch (error) {
                fileListStatus.innerHTML = `
                    <div class="status error">
                        ❌ Error: ${error.message}
                    </div>
                `;
            }
        }

        async function handleUpdateFile(event, fileId) {
            const file = event.target.files[0];
            if (!file) return;

            fileListStatus.innerHTML = '<div class="loading">Updating file...</div>';
            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch(`/files/${fileId}`, {
                    method: 'PUT',
                    body: formData
                });
                const data = await response.json();
                if (!response.ok) {
                    throw new Error(data.detail || 'Failed to update file');
                }
                fileListStatus.innerHTML = `
                    <div class="status success">
                        ✅ File updated. Chunks: ${data.chunks}
                    </div>
                `;
                fetchFiles();
            } catch (error) {
                fileListStatus.innerHTML = `
                    <div class="status error">
                        ❌ Error: ${error.message}
                    </div>
                `;
            } finally {
                event.target.value = '';
            }
        }

        // Auto-load file list on page load
        fetchFiles();
    </script>
</body>
</html>

